package com.workflow.listener;

import com.oa.pojo.User;
import com.oa.service.LeaveService;
import com.oa.service.ReimbursementService;
import com.oa.service.UserService;
import com.oa.utils.MyWebUtils;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;

/**
 * @Author Str
 * @Date 2021/12/17 10:16
 * @Description :
 */
public class ReimbursementTaskHandler implements TaskListener {
    private ReimbursementService reimbursementService;
    private UserService userService;

    public ReimbursementTaskHandler() {
        // 根据上下文加载器从ioc容器中获取bean
        reimbursementService = MyWebUtils.getBean(ReimbursementService.class);
        userService = MyWebUtils.getBean(UserService.class);
    }

    @Override
    public void notify(DelegateTask task) {
        // 1、获取当前处理事务时的用户对象，从会话域拿
        User user = MyWebUtils.getCurrentUser();
        // 2、获取当前用户的角色

        // 3、获取任务ID，流程实例ID
        String taskID = task.getId();
        String proInsID = task.getProcessInstanceId();
        String deptId = user.getDeptId();
        String leaderID = null;
        System.out.println("==================money=========================");
        System.out.println("taskID:"+taskID);
        System.out.println("proInsID:"+proInsID);
        System.out.println("money:"+reimbursementService.queryMoney(proInsID));
        System.out.println("==================money=========================");
        // 4、判断是员工还是领导 leader（部门主管） / employee（雇员）
        String roleId = userService.getRoleId(user.getId());
        // 本部门leader审批
        if (roleId.equals("r03") || roleId.equals("r04") || roleId.equals("r05")) {
            // 根据部门ID获取所在部门领导ID
            leaderID = reimbursementService.getDeptLeaderID(deptId);
        }
        // boss审批，money>200
        // 防止二次进入该选项，所以已经是boss审批的将跳过该选项
        else if (reimbursementService.queryMoney(proInsID) > 200&& !reimbursementService.getAssigneeByProcInstId(proInsID).equals("u03")) {
            leaderID = "u03";
        }
        // 财务主管审批
        else {
            // Tom，u04为经管部领导
            leaderID = "u04";
        }
        // 设置新建节点的办理人
        task.setAssignee(leaderID);
        // 更新t_reimbursementService表(办理人+任务ID)
        System.out.println("====================当前办理人=====================");
        System.out.println("notify.proInsID::" + proInsID);
        System.out.println("notify.taskID::" + taskID);
        System.out.println("notify.leaderID::" + leaderID);
        System.out.println("====================当前办理人=====================");
        reimbursementService.updateAssigneeAndTask(proInsID, taskID, leaderID);
    }
}
